<script setup>
import {ElButton, ElCard, ElInput, ElMessage, ElMessageBox, ElSelect, ElOption, ElImage, ElPagination, ElEmpty, ElText, ElForm, ElFormItem} from "element-plus";
import {Delete, Edit, Refresh, Picture as IconPicture} from "@element-plus/icons-vue";
import {defineProps, onMounted, ref} from "vue";
import {ListUserAnswersByPage, DeleteUserAnswer, ListMyUserAnswersByPage} from "@/api/userAnswer.js";
import AddUserAnswerComponent from "@/components/admin/userAnswerAdmin/AddUserAnswerComponent.vue";
import UpdateUserAnswerComponent from "@/components/admin/userAnswerAdmin/UpdateUserAnswerComponent.vue";

const current = ref(1) //当前页
const pageSize = ref(10) //每页条数
const total = ref(0) //总条数

const props = defineProps({
  appId: {
    type: String,
    default: ""
  }
});
const emit = defineEmits(['data-loaded,row-clicked']);
// 在点击某一行时调用这个方法
const handleRowClick = (row) => {
  emit('row-clicked', row.id); // 触发 row-clicked 事件，并传递行的 id
};
// 表单数据模型
const form = ref({
  // 分页参数
  pageSize: 10,
  current: 1,

  // 排序参数
  sortField: '',
  sortOrder: '',

  // 查询参数
  id: null,
  appId: null,
  appType: null,
  scoringStrategy: null,
  choices: null,
  resultId: null,
  resultName: '',
  resultDesc: '',
  resultPicture: null,
  resultScore: null,
  userId: null,
  notId: null,
  searchText: '',
  isDelete: null
})

const fields = ref({
  "ID": "id",
  "应用ID": "appId",
  "结果ID": "resultId",
  "用户ID": "userId",
  "结果名称": "resultName",
  "得分": "resultScore"
})

const tableData = ref([])

const clearForm = () => {
  form.value = {
    pageSize: 10,
    current: 1,
    sortField: '',
    sortOrder: '',
    id: null,
    appId: null,
    appType: null,
    scoringStrategy: null,
    choices: null,
    resultId: null,
    resultName: '',
    resultDesc: '',
    resultPicture: null,
    resultScore: null,
    userId: null,
    notId: null,
    searchText: '',
    isDelete: null
  }
}

const fetchUserAnswerList = async () => {
  // 构建请求参数
  const params = {
    id: form.value.id && form.value.id > 0 ? form.value.id : null,
    appId: Number(props.appId),
    appType: form.value.appType !== null ? form.value.appType : null,
    scoringStrategy: form.value.scoringStrategy !== null ? form.value.scoringStrategy : null,
    choices: form.value.choices ? form.value.choices : null,
    resultId: form.value.resultId && form.value.resultId > 0 ? form.value.resultId : null,
    resultName: form.value.resultName ? form.value.resultName : null,
    resultDesc: form.value.resultDesc ? form.value.resultDesc : null,
    resultPicture: form.value.resultPicture ? form.value.resultPicture : null,
    resultScore: form.value.resultScore && form.value.resultScore > 0 ? form.value.resultScore : null,
    userId: form.value.userId && form.value.userId > 0 ? form.value.userId : null,
    notId: form.value.notId && form.value.notId > 0 ? form.value.notId : null,
    searchText: form.value.searchText ? form.value.searchText : null,
    sortField: form.value.sortField ? form.value.sortField : null,
    sortOrder: form.value.sortOrder ? form.value.sortOrder : null,
    isDelete: form.value.isDelete !== null ? form.value.isDelete : null,
    current: current.value,
    pageSize: pageSize.value
  }

  try {
    console.log("params: ",params)
    const response = await ListMyUserAnswersByPage(params)
    console.log("response: ",response)
    tableData.value = response.data.UserAnswerList || []
    total.value = response.data.total
    current.value = response.data.current
    pageSize.value = response.data.pageSize
    emit('data-loaded', tableData.value); // 数据加载完成后发射事件
    ElMessage.success("查询成功！")
  } catch (error) {
    ElMessage.error("查询失败：" + error.message)
  }
}

onMounted(async () => {
  await fetchUserAnswerList()
})

// 分页大小变化
const onSizeChange = async (size) => {
  pageSize.value = size
  await fetchUserAnswerList()
}

// 当前页码变化
const onCurrentChange = async (num) => {
  current.value = num
  await fetchUserAnswerList()
}

// 添加用户答案
const addUserAnswerRef = ref(null)
const openAddUserAnswerDialog = () => {
  if (addUserAnswerRef.value) {
    addUserAnswerRef.value.showAddUserAnswerDialog()
  }
}

// 更新用户答案
const updateUserAnswerRef = ref(null)
const openUpdateUserAnswerDialog = (row) => {
  if (updateUserAnswerRef.value) {
    updateUserAnswerRef.value.showUpdateUserAnswerDialog(row)
  }
}

// 删除/恢复用户答案
const DeleteForUserAnswer = async (row) => {
  ElMessageBox.confirm(
      row.isDelete === 0 ? '此操作将删除该用户答案，是否确认删除？' : '此操作将恢复该用户答案，是否确认恢复？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await DeleteUserAnswer(row.id)
        await fetchUserAnswerList()
        ElMessage.success(row.isDelete === 0 ? "删除成功！" : "恢复成功！")
      })
      .catch(() => {
        ElMessage.info('操作已取消')
      })
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>用户答案管理</span>
        <div class="extra">
          <el-button type="primary" @click="openAddUserAnswerDialog">添加用户答案</el-button>
          <AddUserAnswerComponent ref="addUserAnswerRef" @call-parent="fetchUserAnswerList"/>
        </div>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline class="user-answer-list">
      <el-form-item label="结果名称：">
        <el-input v-model="form.resultName" placeholder="请输入结果名称"/>
      </el-form-item>
      <el-form-item label="结果描述：">
        <el-input v-model="form.resultDesc" placeholder="请输入结果描述"/>
      </el-form-item>
      <el-form-item label="结果ID：">
        <el-input v-model="form.resultId" placeholder="请输入结果ID" type="number"/>
      </el-form-item>
      <el-form-item label="是否删除：">
        <el-select v-model="form.isDelete" placeholder="请选择状态" clearable>
          <el-option label="所有" :value="-1"></el-option>
          <el-option label="正常" :value="0"></el-option>
          <el-option label="删除" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序字段：">
        <el-select v-model="form.sortField" placeholder="请选择排序字段" clearable>
          <el-option v-for="([label, value]) in Object.entries(fields)" :key="value" :label="label"
                     :value="value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序方式：">
        <el-select v-model="form.sortOrder" placeholder="请选择排序方式" clearable>
          <el-option label="升序" value="asc"></el-option>
          <el-option label="降序" value="desc"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="button-group">
        <el-button type="primary" @click="fetchUserAnswerList">搜索</el-button>
        <el-button @click="
          clearForm();
          fetchUserAnswerList();
          ElMessage.success('重置成功！');
        ">重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 用户答案列表 -->
    <el-table :data="tableData" style="width: 100%" v-loading="tableData.length === 0" @row-click="handleRowClick">
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="应用ID" prop="appId" disabled="true"></el-table-column>
      <el-table-column label="应用类型" prop="appType" disabled="true">
        <template #default="{row}">
          {{ row.appType === 0 ? '得分类' : '角色测评类' }}
        </template>
      </el-table-column>
      <el-table-column label="评分策略" prop="scoringStrategy" disabled="true">
        <template #default="{row}">
          {{ row.scoringStrategy === 0 ? '自定义' : 'AI' }}
        </template>
      </el-table-column>
      <el-table-column label="用户答案" prop="choices">
        <template #default="{row}">
          <el-tag v-for="(choice, index) in row.choice" :key="index" style="margin-right: 5px; margin-bottom: 5px;">
            {{ choice }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="结果ID" prop="resultId"></el-table-column>
      <el-table-column label="结果名称" prop="resultName"></el-table-column>
      <el-table-column label="结果描述" prop="resultDesc" show-overflow-tooltip></el-table-column>
      <el-table-column label="结果图片" prop="resultPicture">
        <template #default="scope">
          <el-image
              style="width: 60px; height: 60px"
              :src="scope.row.resultPicture || ''"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[scope.row.resultPicture || '']"
              :preview-teleported="true"
              fit="cover"
              v-if="scope.row.resultPicture"
          >
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <icon-picture/>
                </el-icon>
              </div>
            </template>
          </el-image>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="得分" prop="resultScore"></el-table-column>
      <el-table-column label="创建时间" prop="createTime"></el-table-column>
      <el-table-column label="更新时间" prop="updateTime"></el-table-column>
      <el-table-column label="状态" prop="isDelete">
        <template #default="{row}">
          <el-text type="success" v-if="row.isDelete === 0">正常</el-text>
          <el-text type="danger" v-else>已删除</el-text>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{row}">
          <el-button
              :icon="Edit"
              circle
              plain
              type="primary"
              @click="openUpdateUserAnswerDialog(row)"
              title="编辑"
          ></el-button>
          <el-button
              :icon="row.isDelete === 0 ? Delete : Refresh"
              circle
              plain
              :type="row.isDelete === 0 ? 'danger' : 'success'"
              @click="DeleteForUserAnswer(row)"
              :title="row.isDelete === 0 ? '删除' : '恢复'"
          ></el-button>
          <UpdateUserAnswerComponent ref="updateUserAnswerRef" @call-parent="fetchUserAnswerList"/>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
        v-model:current-page="form.current"
        v-model:page-size="form.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="jumper, total, sizes, prev, pager, next"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>
</template>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.user-answer-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.user-answer-list el-form-item {
  margin-bottom: 0;
}

.button-group {
  margin-left: auto;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}
</style>